package com.uubx.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.uubx.exception.CustomerException;
import com.uubx.mapper.UserMapper;
import com.uubx.pojo.Menu;
import com.uubx.pojo.Permission;
import com.uubx.pojo.User;
import com.uubx.result.MessageCode;
import com.uubx.service.PermissionService;
import com.uubx.service.UserLoginService;
import com.uubx.utils.JedisTemplete;
import com.uubx.utils.JsonUtils;
import com.uubx.utils.Md5Utils;
import com.uubx.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;

/**
 * @Author wyy
 * @Date 2020/12/29 16:31
 * @Version 1.0
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private JedisTemplete jedisTemplete;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionService permissionService;

    public static final String LOGIN="xasfasfcsdcdsadacjsdj";

    @Override
    public User login(String username, String password) throws CustomerException {
        //1.判断空
        if (username==null||username.trim().equals("")){
            throw new CustomerException(MessageCode.USERNAME_EMPTY);
        }
        if (password==null||password.trim().equals("")){
            throw new CustomerException(MessageCode.PASSWORD_EMPTY);
        }

        //获取用户的盐
        User userRedis = userMapper.queryUserByUsername(username);
        if(userRedis==null) {
            throw new CustomerException(MessageCode.LOFIN_EMPTY);
        }
        //判断是否激活
        if(userRedis.getStatus()==0){
            throw new CustomerException(MessageCode.USER_EMPTY);
        }
        //获取数据库的盐
        String salt = userRedis.getSalt();

        //加密
        String md5Password = Md5Utils.md5Password(password, salt);
        //对比
        if(!userRedis.getPassword().equals(md5Password)){
            //密码错误
            throw new CustomerException(MessageCode.LOFIN_EMPTY);
        }

        //将密码和盐置空，不显示给前端
        userRedis.setPassword(null);
        userRedis.setSalt(null);

        TokenVo tokenVo=new TokenVo();
        //更新登入时间
        tokenVo.setLastLoginTime(new Date());
        tokenVo.setUsername(username);
        //Map<String,String> result=new HashMap<>();
        User user=new User();
        //查询是否登入
        if (!StringUtils.isEmpty(userRedis.getToken())){
            String value = jedisTemplete.get(LOGIN + userRedis.getToken());
            if(value!=null){
                jedisTemplete.remove(LOGIN + userRedis.getToken());
                userMapper.deleteToken(userRedis.getToken());
                 throw  new CustomerException(MessageCode.LOFINAA_EMPTY);
            }

        }

        // 2、登录成功后生成token。
        String token = UUID.randomUUID().toString().replace("-", "");

        //设置token到数据库
        tokenVo.setToken(token);
        //修改到数据库
        userMapper.updateToken(tokenVo);




        //根据用户username查询菜单
        List<Menu> menuList=permissionService.findMenuListByUsername(username);

        //根据用户username查询权限
        List<Permission> permissionListByUsername = permissionService.findPermissionListByUsername(username);

        //放入权限范围的菜单和权限
        user.setMenus(menuList);
        user.setToken(token);

        userRedis.setPermissions(permissionListByUsername);
        userRedis.setToken(token);

        // 3、把用户信息保存到redis。Key就是token，value就是TbUser对象转换成json。
        // 4、使用String类型保存Session信息。可以使用“前缀:token”为key
        jedisTemplete.set(LOGIN+token, JsonUtils.objectToJson(userRedis));

        // 5、设置key的过期时间。
        jedisTemplete.expire(LOGIN+token,60*60*2);

        return user;
    }

    //退出登入
    @Override
    public void loginOut(String token) {
        jedisTemplete.remove(LOGIN+token);

        userMapper.deleteToken(token);
    }


}
